<?php
/*
 * Created on Sep 4, 2009
 *
 * To change the template for this generated file go to
 * Window - Preferences - PHPeclipse - PHP - Code Templates
 */
?>
<?php
class Model_user extends Model {
	var $_tbl_name;

	function Model_user() {
		// Call the Model constructor
		parent :: Model();
		$this->_tbl_name = "tbl_users";
	}

	/**
	 *
	 *
	 */
	function login($user, $pass){
		$user = addslashes($user);
		$pass = addslashes($pass);
		$sql = "select * from " . $this->_tbl_name . " where (loginname = '$user' || email = '$user') and passwd='" . md5($pass) . "'";
		//echo $sql; exit;

		$query = $this->db->query($sql);
		if ($query->num_rows() > 0) {
			return $query->first_row('array');
		}
		return false;
	}

	/**
	 *
	 *
	 */
	function changepasswd($username, $newpass)
	{
		// Check old passwd
		$data = array('passwd' => $newpass);

		$this->db->where('loginname', $username);
		return $this->db->update($this->_tbl_name, $data);
	}

	/**
	 *
	 *
	 */
	function find($loginname){
		$this->db->where('loginname', "$loginname");
		$query = $this->db->get($this->_tbl_name);	

		if ($query->num_rows() > 0) {
			return $query->first_row('array');
		}
		return null;
	}

	/**
	 *
	 *
	 */
	function update_user($id, $data)
	{
		$this->db->where('id', $id);
		$data['modified_date'] = date("Y-m-d h:i:s");
		return $this->db->update($this->_tbl_name, $data);
	}

	/**
	 *
	 *
	 */
	function check_email($email, $id){
		$this->db->where('email', $email);
		if(intval($id)){
			$this->db->where_not_in('id', $id);
		}
		$query = $this->db->get($this->_tbl_name);
		//echo $this->db->last_query();
		if ($query->num_rows() > 0) {
			return $query->first_row('array');
		}
		return null;
	}

	/**
	 *
	 *
	 */
	function check_loginname($loginname, $id){
		$this->db->where('loginname', $loginname);
		if(intval($id)){
			$this->db->where_not_in('id', $id);
		}
		$query = $this->db->get($this->_tbl_name);
		//echo $this->db->last_query();
		if ($query->num_rows() > 0) {
			return $query->first_row('array');
		}
		return null;
	}
	
	/**
	 * 
	 * 
	 * @return array() 
	 */
	function fetch_by_roles($roles){
		$this->db->where_in($roles);
		$query = $this->db->get($this->_tbl_name);
		//echo $this->db->last_query();
		if ($query->num_rows() > 0) {
			return $query->result_array();
		}
		return null;
	}
}
?>